package com.luonan.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.luonan.mapper.UserArticleMapper;
import com.luonan.pojo.Article;
import com.luonan.pojo.Result;
import com.luonan.service.UserService;
import com.luonan.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 用于管理文章的控制器
 * */

@RestController
//跨域注解
@CrossOrigin
public class WanZhangController {

    @Autowired
    private UserArticleMapper userArticleMapper;

    @GetMapping("/WanZhang")
    public Result getWanZhang() {
        Map<String, Object> clair = ThreadLocalUtil.get();
        Integer UserID = (Integer)clair.get("id");
        List<Article> selecteDateList = userArticleMapper.selectList(new QueryWrapper<Article>().eq("create_user", UserID));
        System.out.println(selecteDateList);
        return Result.success(selecteDateList);
    }

    @PostMapping("/WanZhang")
    public Result addWanZhang(@RequestBody Article article) {
        Map<String, Object> clair = ThreadLocalUtil.get();
        Integer UserID = (Integer)clair.get("id");
        article.setCreateUser(UserID);
        article.setCreateTime(LocalDateTime.now());
        article.setUpdateTime(LocalDateTime.now());
        userArticleMapper.insert(article);
        return Result.success();
    }

    @DeleteMapping("/WanZhang/{id}")
    public Result deleteWanZhang(@PathVariable Integer id) {
        int i = userArticleMapper.deleteById(id);
        if (i == 1) {
            return Result.success();
        } else {
            return Result.error("删除失败");
        }
    }

    @GetMapping("/WanZhang/all")
    public Result getAllWanZhang() {
        return Result.success(userArticleMapper.selectList(null));
    }

    @PutMapping("/WanZhang/{id}")
    public Result updateWanZhang(@PathVariable Integer id, @RequestBody Article article) {
        int i = userArticleMapper.updateById(article);
        if (i==1){
            return Result.success();
        }else {
            return Result.error("更新失败");
        }
    }

}
